package com.itzsj.common.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;

public class JWTUtil {

    public static String createJWT(Map<String, Object> claims, String secretKey, Long ttMillis) {

        SecretKey signKey = Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8));
        Date expiration = new Date(System.currentTimeMillis() + ttMillis);

        JwtBuilder jwtBuilder = Jwts.builder()
                .claims(claims)
                .signWith(signKey)
                .expiration(expiration);

        return jwtBuilder.compact();
    }

    public static Claims parseJWT(String jwtToken, String secretKey) {

        SecretKey signKey = Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8));

        Jws<Claims> claimsJws = Jwts.parser()
                .verifyWith(signKey)
                .build()
                .parseSignedClaims(jwtToken);

        return claimsJws.getPayload();
    }

}
